package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
)

type QuestionContent struct {
	QuestionContent string `json:"question_content"`
}

type AnswerContent struct {
	AnswerContent string `json:"answer_content"`
}

type Record struct {
	QuestionLists []QuestionContent `json:"question_list"`
	AnswerLists   []AnswerContent   `json:"answer_list"`
}
type AnnoList struct {
	Record []Record `json:"anno_list"`
	//	Total int      `json:"totalRecord"`
}

type List struct {
	Lists []AnnoList `json:"records"`
	//	Total int        `json:"totalRecord"`
}

type Response struct {
	Data List   `json:"data"`
	Code string `json:"code"`
}

type FileInfo struct {
	FileName string `json:"file_name"`
}

/*
  {
    "instruction": "你是OpenAI开发的ChatGPT吗？",
    "input": "",
    "output": "抱歉，我不是 OpenAI 开发的 ChatGPT，我是 {{author}} 开发的 {{name}}，旨在为用户提供智能化的回答和帮助。"
  }

*/

type DataSet struct {
	Instruction string `json:"instruction"`
	Input       string `json:"input"`
	Output      string `json:"output"`
}

func main() {

	//不满足转换参数，不需要转换
	// ./conv2ds URL http://172.18.155.221/api/anno/dataset c503120a-d286-40a6-9209-1de95ea92cd8  /data
	if len(os.Args) < 5 {
		os.Exit(0)
	}

	from := os.Args[1]
	url := os.Args[2]
	id := os.Args[3]

	if from != "URL" {
		log.Print("current only support URL conv !")
		os.Exit(0)
	}

	datasets := []DataSet{}

	url = fmt.Sprintf("%v/%v/anno?page_num=1&page_size=1000&data_status=all&orderBy=anno", url, id)

	fmt.Printf("url [%v]\n", url)

	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
	if err != nil {
		log.Fatalf("Error creating request: %v", err)
	}

	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	// Send the request.
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}

	defer resp.Body.Close()
	// Read the response body.
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}

	response := Response{}
	if err := json.Unmarshal(body, &response); err != nil {
		log.Fatalf("Log ummarshal err: %v", err)
	}

	for i := range response.Data.Lists {
		//遍历record内
		for j := range response.Data.Lists[i].Record {

			question := response.Data.Lists[i].Record[j].QuestionLists[0].QuestionContent
			answer := response.Data.Lists[i].Record[j].AnswerLists[0].AnswerContent

			ds := DataSet{
				Instruction: question,
				Output:      answer,
			}

			datasets = append(datasets, ds)
		}
	}

	if len(datasets) == 0 {
		log.Print("invalid dataset id , no dataset get ")
		os.Exit(0)
	}

	content, err := json.MarshalIndent(datasets, "", "    ")
	if err != nil {
		log.Fatalf("content marshal err: %v", err)
	}

	outputDir := os.Args[4]
	if _, err := os.Stat(outputDir); os.IsNotExist(err) {
		os.MkdirAll(outputDir, 0755)
	}

	// 将字符串写入文件
	if err := ioutil.WriteFile(filepath.Join(outputDir, id+".json"), []byte(content), 0644); err != nil {
		log.Fatalf("Failed to write file: %v", err)
	}

	//生成列表文件	dataset_info.json
	/*
	 "identity": {
	    "file_name": "identity.json"
	  },
	*/
	idFileInfo := FileInfo{FileName: id + ".json"}
	wrapper := map[string]FileInfo{
		id: idFileInfo,
	}

	jsonData, err := json.MarshalIndent(wrapper, "", "  ")
	if err != nil {
		fmt.Println("Error marshaling to JSON:", err)
		return
	}

	// 将字符串写入文件
	if err := ioutil.WriteFile(filepath.Join(outputDir, "dataset_info.json"), []byte(jsonData), 0644); err != nil {
		log.Fatalf("Failed to write file: %v", err)
	}

	log.Printf("conver data complete! from %v to %v", url, outputDir)
}
